/**
 * @author: 最新公告
 * @author: YoungYa
 */
import {LeftOutlined, RightOutlined} from '@ant-design/icons';
import {useIntl} from '@umijs/max';
import {useRequest} from 'ahooks';
import {Avatar, Badge, Button, Card, Flex, List, Tag} from 'antd';
import {get} from 'lodash-es';
import {FC, useEffect, useState} from 'react';

import {getAnnouncementList} from '@/services/administrative/announcement';
import {formatPerfix, randomTagColor} from '@/utils';
import {AnnouncementTypeEnum} from '@/utils/const';
import {EVENTBUS_TYPE, ROUTES} from '@/utils/enums';
import eventBus from '@/utils/eventBus';
import {Icon} from "@@/exports";

const LatestAnnouncement: FC = () => {
  // 国际化工具
  const {formatMessage} = useIntl();
  // 翻页参数
  const [current, setCurrent] = useState<number>(1);
  /**
   * @description: 获取最新公告列表
   * @author: YoungYa
   */
  const {data: announcementList, loading: announcementListLoading, run: fetchAnnouncementList} = useRequest(
    async (params) => get(await getAnnouncementList(params), 'data.list', []),
    {
      defaultParams: [{current, pageSize: 5}],
    },
  );

  useEffect(() => {
    fetchAnnouncementList({current, pageSize: 5});
  }, [current]);

  const CardTitle = () => (
    <Flex justify={'space-between'}>
      <div>
        {formatMessage({id: formatPerfix(ROUTES.WORKBENCH, 'latest-announcement')})}
      </div>
      <Flex>
        <Button type={'text'} onClick={() => setCurrent(current - 1)}
                disabled={current <= 1}><LeftOutlined/></Button>
        <Button type={'text'} onClick={() => setCurrent(current + 1)}
                disabled={announcementList?.length < 5}><RightOutlined/></Button>
      </Flex>
    </Flex>
  );
  return (
    <Card
      title={<CardTitle/>}
      loading={announcementListLoading}
      styles={{body: {padding: '5px 24px'}}}
    >
      <List
        itemLayout="horizontal"
        dataSource={announcementList}
        renderItem={(record: API.ANNOUNCEMENT) => (
          <List.Item
            actions={[
              record.pinned ? <Icon icon='bx:bxs-to-top' style={{fontSize: 16, color: '#cf1322'}}/> : null,
              <Tag color={randomTagColor()} key="type">
                {formatMessage({
                  id: formatPerfix(
                    ROUTES.ANNOUNCEMENT,
                    `type.${AnnouncementTypeEnum[record.type]}`,
                  ),
                })}
              </Tag>,
            ]}
          >
            <List.Item.Meta
              avatar={<Avatar src={record.avatar_url}/>}
              title={
                <a onClick={() => eventBus.emit(EVENTBUS_TYPE.ANNOUNCEMENT, record)}>
                  {record.title}
                </a>
              }
              description={record.cn_name}
            />
          </List.Item>
        )
        }
      />
    </Card>
  )
    ;
};
export default LatestAnnouncement;
